<?php
abstract class App_Controller_Action extends Zend_Controller_Action
{
    /**
     * Flash Messenger
     * @var Zend_Controller_Action_Helper_FlashMessenger
     */
    protected $_flash = null;
    
    protected $_model = null;

    
    public function init()
    {
        $this->_flash = $this->_helper->getHelper('FlashMessenger');
        $this->view->flash_messages = $this->_flash->getMessages();
        
        $moduleName = $this->_request->getModuleName();
        if ($moduleName === 'admin') {
            $this->_authorize();
        } else { // $moduleName === 'default'
            $categories = new Category();
            $children = $categories->getChildren(-1, 'product');
            $this->view->categories_options = $this->view->
                categoriesOptions($children, '', '', 'search_id');
            $this->view->product_categories = $children;
        }
    }
    

    /**
     * Go back to previous page
     *
     * @param string $message Flash message
     * @return void
     */
    protected function _goBack($message = '')
    {
        if ($message !== '') {
            $this->_flash->addMessage($message);
        }
        
        if (!isset($_SERVER['HTTP_REFERER'])) {
            throw new Exception('Previous page not exist');
        }
        
        $this->_redirect("{$_SERVER['HTTP_REFERER']}");
    }
    
    
    protected function _getId()
    {
        $id = (int)$this->_getParam('id', 0);
        if ($id <= 0) {
            $this->_goBack('请输入正确的id值');
        }
        
        return $id;
    }
    
    
    protected function _authorize()
    {
        $actionName = $this->_request->getActionName();
        if ($actionName !== 'login') {
            $authSession = new Zend_Session_Namespace('auth');
            if (!$authSession->isAdmin) {
                $controllerName = $this->_request->getControllerName();
                $this->_helper->Redirector('login', 'login', null, 
                    array('forward' => $controllerName));
            }
        }
    }
    
    
    protected function _ensurePost()
    {
        if (!$this->_request->isPost()) {
            throw new Exception('HTTP post request expected');
        }
    }
}